package org.i1510.wx.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.i1510.common.bean.PageBean;
import org.i1510.common.utils.PrintWriterUtils;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.encryption.EncryptUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.i1510.wx.bean.req.ReqBaseMessage;
import org.i1510.wx.constant.MessageConstant;
import org.i1510.wx.dao.IWxPublicDao;
import org.i1510.wx.po.WxPublic;
import org.i1510.wx.po.WxTextMessage;
import org.i1510.wx.service.IWxPublicService;
import org.i1510.wx.service.impl.SendMessageServiceFactory;
import org.i1510.wx.utils.MessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;






@Controller
@RequestMapping(value = "/admin/wxPublic")
public class WxPublicController {
	private static final Logger logger = LoggerFactory.getLogger(WxPublicController.class);
	@Autowired
	private IWxPublicService iWxPublicService;
	@Autowired
	private IWxPublicDao iWxPublicDao;
	
	private ResultMapper mapper;
	
	
	/**
	*@Author Rambo
	*@Desc：公众号接收信息
	*@param request
	*@param response
	*@throws ServletException
	*@throws IOException TODO
	*@Version  WxPublicController.java,v 1.1 2014-10-17 下午3:27:33 
	*/
	@RequestMapping(value = { "/{docId}/message" }, method = {RequestMethod.POST,RequestMethod.GET})
	public void gzhMessage(HttpServletRequest request,
			HttpServletResponse response,@PathVariable("docId") String docId) throws ServletException, IOException {

		WxPublic wxPublic = iWxPublicService.findById(docId);

		String token = wxPublic == null ? "" : wxPublic.getIntToken();
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		
//		String token = "rambo_zxhy";
//校验签名
		String[] ArrTmp = { token, timestamp, nonce };
		Arrays.sort(ArrTmp);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ArrTmp.length; i++) {
			sb.append(ArrTmp[i]);
		}
		String pwd = EncryptUtils.EncryptMethod(sb.toString());
		PrintWriter printWriter = response.getWriter();

		System.out.println("->校验之前："+signature+","+timestamp+","+nonce+","+echostr+","+pwd);
		
		if(request.getMethod().equals("GET")){
			//校验
			System.out.println("GET---->");			
			if (pwd.equals(signature)) {
				System.out.println("->校验之后："+signature+","+timestamp+","+nonce+","+echostr+","+pwd);
				if (!"".equals(echostr) && echostr != null) {
					printWriter.print(echostr);
				}
			}
			printWriter.close();
			printWriter = null;
		}else if(request.getMethod().equals("POST")){
			System.out.println("POST---->");
			try {
				String respMessage = "";
				if (pwd.equals(signature)) {
					ReqBaseMessage reqMessage = MessageUtils.tranMessage(request, wxPublic);
					if (reqMessage == null) {
						return;
					}
					
					request.setCharacterEncoding("UTF-8");
					
					
//					// 通知
//					applicationContext.publishEvent(new RequestEvent(rbMessage, this,
//							id, request, response));
					
//					// 调用核心业务类接收消息、处理消息
//					lweChatService.processRequest(rbMessage, wePublic, response);
					respMessage = SendMessageServiceFactory.getSendMessageService(wxPublic).sendMessage(reqMessage,wxPublic);				

				}
				PrintWriterUtils write = new PrintWriterUtils();
				write.sendPrintWriterUtils(response, respMessage, "plain");
							
		
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
	}
	
	@RequestMapping(value = "/api", method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	@Deprecated
	public String api(ReqBaseMessage rbMessage,HttpServletRequest request,@Valid @ModelAttribute("wxPublic") WxPublic wxPublic,BindingResult errors) {
		
		String respMessage = "";
		// 发送方帐号（open_id）
		String fromUserName = rbMessage.getFromUserName();
		// 消息类型
		String msgType = rbMessage.getMsgType();
		// 公众号
		String toUserName = wxPublic.getQrcode();
		
		System.out.println("msgType:"+msgType);
		
		if (msgType.equals(MessageConstant.REQ_MESSAGE_TYPE_TEXT)) {
			
		}

		try {
			respMessage = SendMessageServiceFactory.getSendMessageService(wxPublic).sendTextMessage(toUserName, fromUserName, "hello world!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
		

	}
	/**
	*@Author Rambo
	*@Desc：提供bootstrap使用
	*@param limit
	*@param offset
	*@param search
	*@param fromDate
	*@param toDate
	*@param wxPublic
	*@param pageBean
	*@param errors
	*@return TODO
	*@Version  WxPublicController.java,v 1.1 2014-11-19 下午3:38:08 
	*/
	@RequestMapping(value = "/jqList", method = RequestMethod.GET)
	@ResponseBody
	public String jqList(@ModelAttribute("limit") String limit,@ModelAttribute("offset") String offset,@ModelAttribute("search") String search,
					@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,
					@Valid @ModelAttribute("wxPublic") WxPublic wxPublic,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			if(!StringUtils.isStringEmpty(limit) && !StringUtils.isStringEmpty(offset) ){
				pageBean.setPageNo(String.valueOf(StringUtils.String2Integer(offset)/StringUtils.String2Integer(limit)+1));
				pageBean.setPageSize(limit);
			}
			List  wxTextMessages = iWxPublicService.getPage(wxPublic, pageBean,conditions);
			int totalCount =  iWxPublicService.getPageCount(wxPublic,conditions);
		
			mapperRtn.appendResult("total", totalCount);
			mapperRtn.appendResult("rows",wxTextMessages);		
		}		
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：保存对象
	*@param wxPublic
	*@param errors
	*@return TODO
	*@Version  WxPublicController.java,v 1.1 2013-11-15 下午4:20:56 
	*/
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request,@Valid @ModelAttribute("wxPublic") WxPublic wxPublic,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iWxPublicService.save(wxPublic,request);
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：删除对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  WxPublicController.java,v 1.1 2014-9-2 下午3:38:17 
	*/
	@RequestMapping(value = "/deleteX", method = RequestMethod.POST)
	@ResponseBody
	public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iWxPublicService.delete(docId);
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：查看对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  WxPublicController.java,v 1.1 2014-9-2 下午3:39:35 
	*/
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	@ResponseBody
	public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			WxPublic wxPublic = iWxPublicService.findById(docId);
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", wxPublic);
		}		
		return mapperRtn.toJson();
	}
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public String list(@ModelAttribute("fromDate") String fromDate,@ModelAttribute("toDate") String toDate,@Valid @ModelAttribute("wxPublic") WxPublic wxPublic,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			List  wxPublics = iWxPublicService.getPage(wxPublic, pageBean,conditions);
			int totalCount =  iWxPublicService.getPageCount(wxPublic,conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData",wxPublics);
			
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}		
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：状态修改
	*@param request
	*@param docId
	*@param docStatus
	*@param errors
	*@return TODO
	*@Version  CateController.java,v 1.1 2014-9-11 上午10:06:04 
	*/
	@RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(docId)){
				WxPublic wxPublic = new WxPublic();
				
				wxPublic.setDocId(docId);
				wxPublic.setDocStatus(docStatus);
				mapper = iWxPublicService.save(wxPublic,request);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}
			
		}
		
		return mapper.toJson();
	}
}